package simulation;

import view.View;

/**
 * @author  Owner
 */
public class Mover implements Runnable {

	private int indexA;
	private int indexB;
	
	private boolean pause;

	private boolean skip;

	private static long speed = 5;
	
	public Mover(int firstInd, int secondInd) {
		this.indexA = firstInd;
		this.indexB = secondInd;
	}

	@SuppressWarnings("deprecation")
	public void run() {
		while (Painter.getInstance().getDynamicSimulators()[indexA].x != Painter.getInstance().getTargets()[indexB]) {
		    
		    synchronized (this) {
			if(pause){
			    try {
				wait();
			    } catch (InterruptedException e) {
				e.printStackTrace();
			    }
			}
			if(skip){
			    skip = false;
			    break;
			}
		    }
		    
		    
			if (indexA < indexB) {
				Painter.getInstance().getDynamicSimulators()[indexA].incrementX();
				Painter.getInstance().getDynamicSimulators()[indexB].decrementX();
			} else {
				Painter.getInstance().getDynamicSimulators()[indexA].decrementX();
				Painter.getInstance().getDynamicSimulators()[indexB].incrementX();
			}
			if (!View.getInstance().getCanvas().isDisposed()) {
				View.getInstance().getCanvas().getDisplay().asyncExec(
						new Runnable() {
							public void run() {
								if (!View.getInstance().getCanvas().isDisposed())
								View.getInstance().getCanvas().redraw();
							}
						});
			}
			else{
				Thread.currentThread().stop();
			}
			try {
				/**
				 * TODO:
				 */
				synchronized (this) {
					Thread.sleep(speed);					
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		IntSimulator tmp = (IntSimulator) Painter.getInstance().getDynamicSimulators()[indexA].clone();
		Painter.getInstance().getDynamicSimulators()[indexA] = (IntSimulator) Painter.getInstance().		getDynamicSimulators()[indexB].clone();
		Painter.getInstance().getDynamicSimulators()[indexB] = tmp;
	}

	public synchronized void pause() {
	    pause = true;
	}
	
	public synchronized void resume(){
	    pause = false;
	    notify();
	}
	public synchronized void skip() {
	    skip = true;
	}

	/**
	 * @param speed  the speed to set
	 * @uml.property  name="speed"
	 */
	/**
	 * TODO:
	 */
	public synchronized static void setSpeed(long speed) {
	    Mover.speed = speed;
	}
	/**
	 * @return  the speed
	 * @uml.property  name="speed"
	 */
	/**
	 * TODO:
	 */
	public synchronized static long getSpeed(){
		return speed;
	}
}
